const MessageRepository = require("../repositories/messageRepositories");

class MessageServices {
  // 提取通用的响应处理函数
  handleResponse(data, error, notFoundMessage = "消息不存在") {
    if (error) {
      return {
        code: 1,
        msg: error.message,
        statusCode: error.statusCode || 500,
      };
    }
    if (!data) {
      return {
        code: 1,
        msg: notFoundMessage,
        statusCode: 404,
      };
    }
    return {
      code: 0,
      data: data,
    };
  }

  /**
   * 新增站内信
   * @param {Object} msgData - 消息数据
   * @returns {Promise<Object>} - 返回响应对象
   */
  async addNewMsg(msgData) {
    try {
      const newMsg = await MessageRepository.addNewMsg(msgData);
      return this.handleResponse(newMsg);
    } catch (error) {
      return this.handleResponse(null, error);
    }
  }

  /**
   * 根据 ID 删除站内信
   * @param {number} id - 消息ID
   * @returns {Promise<Object>} - 返回响应对象
   */
  async delMsgById(id) {
    try {
      const result = await MessageRepository.delMsgById(id);
      return result
        ? this.handleResponse("消息删除成功")
        : this.handleResponse(null, null, "消息不存在");
    } catch (error) {
      return this.handleResponse(null, error);
    }
  }

  /**
   * 获取全部站内信（带分页和过滤）
   * @param {Object} query - 查询参数（page, size, title, sendId, acceptId, isRead, isSystem）
   * @returns {Promise<Object>} - 返回响应对象
   */
  async getAllMsgs(query) {
    try {
      const {
        page = 1,
        size = 10,
        title,
        sendId,
        acceptId,
        isRead,
        isSystem,
      } = query;
      const offset = (page - 1) * size;
      const limit = parseInt(size);

      // 调用数据持久层获取分页和过滤后的消息
      const messages = await MessageRepository.getAllMsgs(offset, limit, {
        title: title ? title.toString() : undefined, // 确保 title 是字符串
        sendId: sendId ? parseInt(sendId) : undefined, // 转换为数字
        acceptId: acceptId ? parseInt(acceptId) : undefined, // 转换为数字
        isRead: isRead
          ? isRead === "true" || isRead === "yes"
            ? "yes"
            : "no"
          : undefined, // 规范化 isRead
        isSystem: isSystem
          ? isSystem === "true" || isSystem === "yes"
            ? "yes"
            : "no"
          : undefined, // 规范化 isSystem
      });

      // 获取总条数
      const total = await MessageRepository.countMessages({
        title: title ? title.toString() : undefined,
        sendId: sendId ? parseInt(sendId) : undefined,
        acceptId: acceptId ? parseInt(acceptId) : undefined,
        isRead: isRead
          ? isRead === "true" || isRead === "yes"
            ? "yes"
            : "no"
          : undefined,
        isSystem: isSystem
          ? isSystem === "true" || isSystem === "yes"
            ? "yes"
            : "no"
          : undefined,
      });

      return this.handleResponse({ data: messages, total });
    } catch (error) {
      console.error("Error in getAllMsgs service:", error);
      return this.handleResponse(null, error);
    }
  }

  /**
   * 根据发送人ID查找站内信
   * @param {number} sendId - 发送人ID
   * @param {string} [isRead] - 是否已读（可选）
   * @returns {Promise<Object>} - 返回响应对象
   */
  async getMsgBySendId(sendId, isRead = null) {
    try {
      const msgs = await MessageRepository.getMsgBySendId(sendId, isRead);
      return this.handleResponse(msgs);
    } catch (error) {
      return this.handleResponse(null, error);
    }
  }

  /**
   * 根据接收人ID查找站内信
   * @param {number} acceptId - 接收人ID
   * @param {string} [isRead] - 是否已读（可选）
   * @returns {Promise<Object>} - 返回响应对象
   */
  async getMsgByAcceptId(acceptId, isRead = null) {
    try {
      const msgs = await MessageRepository.getMsgByAcceptId(acceptId, isRead);
      return this.handleResponse(msgs);
    } catch (error) {
      return this.handleResponse(null, error);
    }
  }

  /**
   * 根据ID设置站内信为已读状态
   * @param {number} id - 消息ID
   * @returns {Promise<Object>} - 返回响应对象
   */
  async setMsgAsReadById(id) {
    try {
      const result = await MessageRepository.setMsgAsReadById(id);
      return result
        ? this.handleResponse("消息已标记为已读")
        : this.handleResponse(null, null, "消息不存在");
    } catch (error) {
      return this.handleResponse(null, error);
    }
  }

  /**
   * 获取来自系统的站内信
   * @returns {Promise<Object>} - 返回响应对象
   */
  async getSystemMsgs() {
    try {
      const msgs = await MessageRepository.getSystemMsgs();
      return this.handleResponse(msgs);
    } catch (error) {
      return this.handleResponse(null, error);
    }
  }

  /**
   * 根据 ID 更新站内信
   * @param {number} id - 消息 ID
   * @param {Object} msgData - 更新数据
   * @returns {Promise<Object>} - 返回响应对象
   */
  async updateMsgById(id, msgData) {
    try {
      const result = await MessageRepository.updateMsgById(id, msgData);
      return result
        ? this.handleResponse("消息更新成功")
        : this.handleResponse(null, null, "消息不存在");
    } catch (error) {
      return this.handleResponse(null, error);
    }
  }
}

module.exports = new MessageServices();
